/**
 * Created by haowanh5 on 2016/11/1.
 */

"use strict";

const Ws = require("ws");
const Logger = require("pomelo-logger").getLogger("PacketHandler", __filename);

const APIStaticConfig = require("../Configs/APIStaticConfig.json");

function PacketHandler(gameServer, socket) {
    this.gameServer = gameServer;
    this.socket = socket;
    this.protocolVersion = 0;

    // Processing Packet Handler

}

module.exports = PacketHandler;

PacketHandler.prototype.handleMessage = function (message) {
    if (message.length === 0) {
        return;
    }

    // Todo Parse Message
    var data = JSON.parse(message);
    var packetId = data.packetId;
    // Logger.info("Receive Client Message [ %s ] [ %s ]", this.socket.playerTracker.playerID, message);
    switch (packetId) {
        // On Connection Start
        case APIStaticConfig.ON_CONNECTION_START:
            Logger.debug("Trigger Connection Start Packet [ %s ]", packetId);
            break;

        // On Connection Reconnect
        case APIStaticConfig.ON_CONNECTION_RECONNECT:
            break;




        // Set Nickname
        case APIStaticConfig.ON_SET_NICKNAME:
            Logger.debug("Trigger Set Nickname Packet [ %s ]", packetId);
            this.socket.playerTracker.setName(data.nickname);
            break;

        // Send Chat Message
        case APIStaticConfig.ON_SEND_CHAT_MESSAGE:
            Logger.debug("Trigger Chat Message Pecket [ %s ]", packetId);
            break;




        // Set Protocol Version, Maybe Some Logic Will Change Online, Then We Can Use This Version
        case APIStaticConfig.ON_SET_PROTOCOL_VERSION:
            Logger.debug("Trigger Set Protocol Version Packet [ %s ]", packetId);

            this.socket.packetHandler.protocolVersion = data.protocolVersion;

            var client = this.socket.playerTracker;
            this.socket.sendPacket(APIStaticConfig.TO_CLEAR_MAP, {});
            this.gameServer.spawnPlayer(client);
            break;

        // Enter Observe Mode
        case APIStaticConfig.ON_SET_OBSERVE_MODE:
            Logger.debug("Trigger Set Observe Mode [ %j ]", packetId);
            setInterval(function () {
                // Todo Get All Player In A Map
                this.socket.playerTracker.isObserver = true;
                var allPlayer = [];
                this.gameServer.players.forEach(player => {
                    allPlayer.push({
                        objectId: player.objectId,
                        position: player.position,
                        screen: {
                            "height": this.gameServer.config.viewHeight,
                            "width": this.gameServer.config.viewWidth
                        },
                        isBot: player.isBot
                    });
                });
                this.socket.sendPacket(APIStaticConfig.TO_UPDATE_POSITION, {
                    "mapInfo": {
                        "height": this.gameServer.config.borderBottom - this.gameServer.config.borderTop,
                        "width": this.gameServer.config.borderRight - this.gameServer.config.borderLeft
                    },
                    "allPlayer": allPlayer
                });
            }.bind(this), this.gameServer.config.tickObserver);
            break;

        case APIStaticConfig.ON_SET_BOT:
            Logger.debug("Trigger Set I AM BOT !!! [ %s ]", packetId);
            this.socket.playerTracker.player.isBot = true;
            break;

        // Set Target
        case APIStaticConfig.ON_SET_TARGET:
            // Logger.debug("Trigger Set Target Packet [ %s ]", packetId);
            // rotation, radian, x and y => rotation, radian, and vector(x, y)
            Logger.debug("Receive Move Data Is [ %j ]",data);
            this.socket.playerTracker.setTarget(data.rotation, data.radian, data.x, data.y);
            break;

        // Use Props
        case APIStaticConfig.ON_USE_PROPS:
            Logger.debug("Trigger Use Props Packet [ %s ] [ %j ]", packetId, data);
            this.socket.playerTracker.useProps(data.propsId, data.position);
            break;

        default:
            break;
    }
};

Ws.prototype.sendPacket = function (packetId, message) {
    // Todo Encrypt Message
    if (this.readyState == Ws.OPEN) {
        message.packetId = packetId;
        var data = JSON.stringify(message);
        // Logger.debug("Send Server Message  [ %j ]", data);
        this.send(data, function (err) {
            if (err) Logger.error("Server Send Data To Client Return Error: ", err);
        });
    } else {
        this.readyState = Ws.CLOSED;
        this.emit('close');
        this.removeAllListeners();
    }
};